package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.IAddressBookService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 地址簿 服务实现类
 * </p>
 *
 * @author chensheng
 * @since 2025-08-08
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {

    @Override
    public AddressBook getDefault() {
        LambdaQueryWrapper<AddressBook> qw = new LambdaQueryWrapper<>();
        qw.eq(AddressBook::getIsDefault, 1);
        qw.eq(AddressBook::getUserId, BaseContext.getCurrentId());
        return this.getOne(qw);
    }

    @Override
    @Transactional
    public void setDefault(AddressBook addressBook) {
        // 将当前用户的所有地址设置为非默认地址
        LambdaQueryWrapper<AddressBook> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AddressBook::getUserId, BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        this.update(addressBook, wrapper);
        
        // 将指定ID的地址设置为默认地址
        AddressBook defaultAddress = new AddressBook();
        defaultAddress.setId(addressBook.getId());
        defaultAddress.setIsDefault(1);
        this.updateById(defaultAddress);
    }

}
